from rest_framework import viewsets, status
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from django_filters import FilterSet, CharFilter, NumberFilter
from .models import Movie, Category
from .serializers import MovieSerializer, CategorySerializer
from django.http import Http404
from rest_framework.permissions import IsAuthenticated
from .permissions import IsAdminOrReadOnly


class MovieFilter(FilterSet):
    """
    电影过滤器类
    - movie_name: 电影名称模糊搜索
    - category: 分类ID精确匹配
    - region: 地区精确匹配
    """
    movie_name = CharFilter(field_name='movie_name', lookup_expr='icontains')
    category = NumberFilter(field_name='category_id')
    region = CharFilter(field_name='region')
    
    class Meta:
        model = Movie
        fields = ['movie_name', 'category', 'region']


class BaseViewSet(viewsets.ModelViewSet):
    """
    基础视图集，提供统一的响应格式
    """
    def get_standard_response(self, code, message, data=None):
        return {
            "code": code,
            "message": message,
            "data": data
        }


class MovieViewSet(BaseViewSet):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer
    filter_backends = [DjangoFilterBackend]  # 只使用 django_filters
    filterset_class = MovieFilter         # 使用自定义的过滤器类

    def get_permissions(self):
        """权限控制"""
        if self.action in ['list', 'retrieve']:
            permission_classes = []
        else:
            permission_classes = [IsAdminOrReadOnly]
        return [permission() for permission in permission_classes]

    def get_queryset(self):
        """
        重写 get_queryset 方法，添加过滤逻辑
        """
        queryset = Movie.objects.all()
        
        # 获取查询参数
        category = self.request.query_params.get('category', None)
        region = self.request.query_params.get('region', None)
        
        # 应用过滤条件
        if category:
            queryset = queryset.filter(category_id=category)
        if region:
            queryset = queryset.filter(region=region)
            
        return queryset

    def list(self, request, *args, **kwargs):
        try:
            # 获取搜索关键词
            search_keyword = request.query_params.get('movie_name', '')
            
            response = super().list(request, *args, **kwargs)
            return Response(self.get_standard_response(
                code=200,
                message="获取电影列表成功",
                data={
                    "total": response.data['count'],
                    "items": response.data['results'],
                    "search_keyword": search_keyword  # 添加搜索关键词到响应中
                }
            ))
        except Exception as e:
            return Response(
                self.get_standard_response(
                    code=500,
                    message=f"获取电影列表失败：{str(e)}",
                    data=None
                ),
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def retrieve(self, request, *args, **kwargs):
        """
        获取电影详情
        """
        try:
            response = super().retrieve(request, *args, **kwargs)
            return Response(self.get_standard_response(
                code=200,
                message="获取电影详情成功",
                data=response.data
            ))
        except Http404:  # 现在应该能正确捕获 404 异常了
            return Response(
                self.get_standard_response(
                    code=404,
                    message="电影不存在",
                    data=None
                ),
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            print(f"获取电影详情出错: {e}")
            return Response(
                self.get_standard_response(
                    code=500,
                    message=f"获取电影详情失败：{str(e)}",
                    data=None
                ),
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


class CategoryViewSet(BaseViewSet):
    """
    分类视图集
    只提供读取功能，不允许修改
    """
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [IsAdminOrReadOnly]  # 添加权限类

    def list(self, request, *args, **kwargs):
        try:
            response = super().list(request, *args, **kwargs)
            return Response(self.get_standard_response(
                code=200,
                message="获取电影分类成功",
                data={
                    "total": response.data['count'],
                    "items": response.data['results']
                }
            ))
        except Exception as e:
            return Response(
                self.get_standard_response(
                    code=500,
                    message=f"获取电影分类失败：{str(e)}",
                    data=None
                ),
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    